package com.tkp.token.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.tkp.entity.ToKenDTO;
import com.tkp.token.service.CallbackService;
import com.tkp.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

/**
 * @Author: duk
 * @Date: 2021/11/3 10:17
 * @Description: 获取toKen实现
 */
@Service
public class CallbackServiceImpl implements CallbackService {

    @Value("${token.tokenAvailableTime}")
    private Long tokenAvailableTime;
    @Resource
    private RedisUtils redisUtils;

    @Override
    public ToKenDTO queryToken(String clientId) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, Math.toIntExact(tokenAvailableTime));
        ToKenDTO dataDTO = new ToKenDTO();
        dataDTO.setTokenAvailableTime(tokenAvailableTime);
        dataDTO.setOperatorCode(clientId);
        //先查询redis是否有存储
        String redisToKen = (String)redisUtils.get(clientId);
        if (ObjectUtil.isNotNull(redisToKen)){
            Long expireTime = redisUtils.getExpireTime(clientId);
            dataDTO.setTokenAvailableTime(expireTime);
            dataDTO.setAccessToken(redisToKen);
            return dataDTO;
        }
        String token= JWT.create().withAudience(clientId).
                withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(clientId));
        dataDTO.setAccessToken(token);
        //存入Redis
        redisUtils.set(clientId,token,(tokenAvailableTime-500), TimeUnit.SECONDS);
        return dataDTO;
    }
}
